"use strict";

import clear from 'rollup-plugin-clear';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from 'rollup-plugin-typescript2';
import screeps from 'rollup-plugin-screeps';
import copy from 'rollup-plugin-copy'
import html from 'rollup-plugin-html'

// let cfg;
// const dest = process.env.DEST;
// if (!dest) {
//   console.log("No destination specified - code will be compiled but not uploaded");
// } else if ((cfg = require("./screeps.json")[dest]) == null) {
//   throw new Error("Invalid upload destination");
// }

let config
// 根据指定的目标获取对应的配置项
if (!process.env.DEST) console.log("未指定目标, 代码将被编译但不会上传")
else if (!(config = require("./screeps.json")[process.env.DEST])) {
    throw new Error("无效目标，请检查 secret.json 中是否包含对应配置")
}

// 根据指定的配置决定是上传还是复制到文件夹
const deployPlugin = config && config.copyPath ?
  // 复制到指定路径
  copy({
    targets: [
      {
        src: 'dist/main.js',
        dest: config.copyPath
      },
      {
        src: 'dist/main.js.map',
        dest: config.copyPath,
        rename: name => name + '.map.js',
        transform: contents => `module.exports = ${contents.toString()};`
      }
    ],
    hook: 'writeBundle',
    verbose: true
  }) :
  // 更新 .map 到 .map.js 并上传
  screeps({ config, dryRun: !config })

export default {
  input: "src/main.ts",
  output: {
    file: "dist/main.js",
    format: "cjs",
    sourcemap: true
  },

  plugins: [
    clear({ targets: ["dist"] }),
    // resolve({ rootDir: "src" }),
    resolve(),
    commonjs(),
    // 构建可能存在的 html 文件
    html({
      include: '**/*.html',
      htmlMinifierOptions: {
        collapseWhitespace: true,
        collapseInlineTagWhitespace: true,
        minifyCSS: true,
        removeComments: true
      }
    }),
    typescript({ tsconfig: "./tsconfig.json" }),
    // screeps({ config: cfg, dryRun: cfg == null })
    deployPlugin
  ]
}
